<?php

namespace app\admin\controller;

use app\admin\model\UserBucket;
use app\common\controller\AdminController;
use app\common\service\RedisService;
use app\webapi\controller\ApiOss;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\Exception;
use think\facade\Config;
use think\facade\Db;
use dh2y\qrcode\QRcode;
use think\facade\Env;

/**
 * @ControllerAnnotation(title="用户")
 */
class Userss extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\User();
        
    }
    

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            
            foreach($where as $key =>&$val){
                if($val[0] == 'payee'){
                    $val[0] = 'payee_bankno';
                }
            }

            $admin = session("admin");

            $count = $this->model
                ->where($where)
                ->where("state <> -1")
                ->whereRaw("bucket_id=:id1 OR bucket_id=:id2", ['id1' => $admin['uid'] , 'id2' => 0 ])
                ->count();
            $list = $this->model
                ->where($where)
                ->where("state <> -1")
                ->whereRaw("bucket_id=:id1 OR bucket_id=:id2", ['id1' => $admin['uid'] , 'id2' => 0 ])
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
//echo Db::getLastSql(); die;
            $bucket = new UserBucket();
            $b = $bucket->find($admin['uid']);
//dump($b);die;
//echo 33;die;
            foreach($list as &$val){
                //银行信息
                $val['payee'] = "收款人:".$val['payee_name']."<br/>银行卡:".$val['payee_bankno']."<br/>开户行:".$val['payee_bankname'];
                //推荐人
                if($val['level1_recommender']){
                    $re = $this->model->find($val['level1_recommender']);
                    $val['recommender'] = $re ? "推荐人:".$re['nickname']."<br/>手机号:".$re['phone'] : '-未找到';
                } else {
                    $val['recommender'] = "--";
                }
                //仓库类型
                //$val['bucket'] = 111 ;// Db::name("user_bucket")->find($val['bucket_id'])["bucket_name"];
                $val['bucket'] = $val['bucket_id'] ? $b->bucket_name : '--' ;

                //是否为管理员
//                if(empty($val['admin_token'])){
//                    $val['is_admin'] = "<span style='color:red'>否</span>";
//                } else {
//                    $val['is_admin'] = "<span style='color:green'>是</span>";
//                }
                
            }
            
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        
        $admin = session('admin');//
        $param = [];
        if(!empty($admin['uid'])){
            $param['bucket_id'] = $admin['uid'];
        }

        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                // $level1_recommender_info = $this->model->where(['phone' => $post['level1_recommender_phone']])->find();
                // if($level1_recommender_info){
                //     $post['level1_recommender'] = $level1_recommender_info['id'];
                // }
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        // if($row['level1_recommender']){
        //     $row['level1_recommender_phone'] = $this->model->find($row['level1_recommender'])['phone'];
        // } else {
        //     $row['level1_recommender_phone'] = "";
        // } 
        $userlist = Db::name("user")->where($param)->select();

        $this->assign('userlist', $userlist);
        $this->assign('row', $row);
        return $this->fetch();
    }



        /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $this->model->whereIn('id', $id)->update(['state' => -1]);
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    //批量修改特权
    public function tequan(){
        
        $id = $this->request->get("id");
        
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            
            try {
                //批量修改
                $save = $this->setGodStates($post) ;
                //print_r($re); die;
                //$save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign("id", $id);
        return $this->fetch();

    }

    //修改账户状态
    public function updatestate($id){
        $this->checkPostRequest();
        $row = $this->model->where(['id' => $id])->find();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            if($row['state'] == 0){
                $param['state'] = 1;
            } else {
                $param['state'] = 0;
            }
            $save = $row->where(["id" => $id])->update($param);
        } catch (\Exception $e) {
            $this->error('修改失败');
        }
        $save ? $this->success('修改成功') : $this->error('修改失败');
    }

    //银行卡信息是否可编辑
    public function updatebank($id){
        $this->checkPostRequest();
        $row = $this->model->where(['id' => $id])->find();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            if($row['edit_bank_access'] == 0){
                $param['edit_bank_access'] = 1;
            } else {
                $param['edit_bank_access'] = 0;
            }
            $save = $row->where(["id" => $id])->update($param);
        } catch (\Exception $e) {
            $this->error('修改失败');
        }
        $save ? $this->success('修改成功') : $this->error('修改失败');
    }

    //恶意用户
    public function updatebad($id){
        $this->checkPostRequest();
        $row = $this->model->where(['id' => $id])->find();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            if($row['bad'] == 0){
                $param['bad'] = 1;
            } else {
                $param['bad'] = 0;
            }
            $save = $row->where(["id" => $id])->update($param);
        } catch (\Exception $e) {
            $this->error('修改失败');
        }

        // $save ? self::setBad($id, $param['bad']) : true;
        $save ? $this->success('修改成功') : $this->error('修改失败');
    }

    //用户订单查看
    public function orders($id){
        //出售订单
        $sale = Db::name("user_order")->alias('a')
        ->join("user_order_payimg b","a.id = b.order_id")
        ->join("user u","a.uid = u.id")
        ->join("user uu","a.saler_id = uu.id")
        ->join("goods_rush g","a.gid = g.id")
        ->field("a.*,u.nickname as buyer,uu.nickname as saler,b.img,g.name as goodsname")
        ->where("saler_id=$id AND a.state > -1")
        ->order("a.create_time DESC")
        ->select();
        
        //购买订单
        $buy = Db::name("user_order")->alias('a')
        ->join("user_order_payimg b","a.id = b.order_id")
        ->join("user u","a.uid = u.id")
        ->join("user uu","a.saler_id = uu.id")
        ->join("goods_rush g","a.gid = g.id")
        ->field("a.*,u.nickname as buyer,uu.nickname as saler,b.img,g.name as goodsname")
        ->where("a.uid=$id AND a.state > -1")
        ->order("a.create_time DESC")
        ->select();

        //抢购商品
        $qiang = Db::name("goods_rush")->alias('a')
        ->join("goods_rush b","a.id = b.id")
        ->join("user c","c.id = a.last_belong")
        ->join("user d","d.id = a.rusher_id")
        ->field("a.*,b.name,b.code,b.img,c.nickname last_belong_nickname,c.avatar last_belong_avatar,c.phone last_belong_phone,
        c.payee_name last_belong_payee_name,c.payee_bankname last_belong_payee_bankname,c.payee_bankno last_belong_payee_bankno,c.wxpay_img last_belong_wxpay_img,c.alipay_img last_belong_alipay_img,
        d.nickname rusher_nickname,d.avatar rusher_avatar,d.phone rusher_phone,d.payee_name rusher_payee_name,d.payee_bankname rusher_payee_bankname,
        d.payee_bankno rusher_payee_bankno,d.wxpay_img rusher_wxpay_img,d.alipay_img rusher_alipay_img")
        ->where(['a.belong' => $id])
        ->order("a.create_time DESC")
        ->select();

        //粉丝
        $fans = Db::name("user")
        ->where(" level1_recommender=$id OR level2_recommender=$id")
        ->field("id,nickname,avatar,phone,level1_recommender,level2_recommender,create_time")
        ->select();
        $fans = $fans->toArray();
        
       foreach($fans as &$val){
            if($val['level1_recommender'] == $id){
                $val['level'] = "一级粉丝";
            }
            if($val['level2_recommender'] == $id){
                $val['level'] = "二级粉丝";
            }
            
       }
       
       


        $this->assign("sale", $sale);
        $this->assign("buy", $buy);
        $this->assign("qiang", $qiang);
        $this->assign("fans", $fans);
        return $this->fetch();
    }

    //查看用户订单
    public function fanorder(){
        $userid = request()->get("userid");

        $order = Db::name("user_order")->alias('a')
        ->join("user_order_payimg b","a.id = b.order_id")
        ->join("user u","a.uid = u.id")
        ->join("user uu","a.saler_id = uu.id")
        ->join("goods_rush g","a.gid = g.id")
        ->field("a.*,u.nickname as buyer,uu.nickname as saler,b.img,g.name as goodsname")
        ->where("a.uid=$userid AND a.state > -1")
        ->order("a.create_time DESC")
        ->select();

        $this->assign("order", $order);
        return $this->fetch();
    }

    //开启分仓
    public function addbucket($id){

    }

    // 设置用户推荐人      TODO 延后
    public function setUserRecommender(){}


    //移除所有用户特权（提前抢购时间和提前抢购数量限制）     -- 清除勾选的用户限制,  目前没有做数据权限验证
    public function removeVip($id){
        foreach($id as &$val){
            RedisService::select(2)->del( self::KEYS['USER_LIMIT'] . "{$val}" );    // $val 必须要字符串类型
            RedisService::select(2)->del( self::KEYS['USER_GODTIME'] . "{$val}" );
            RedisService::select(2)->del( 'user_god_ttl_' . "{$val}" );
            //获取这个用户特权 成功的键  所有场次
           $special_success = RedisService::select(2)->keys('special_success_'.$val.'_*');
           foreach ($special_success as $sv){
               RedisService::select(2)->del( $sv);
           }
        }
//        $allKeys = RedisService::select(2)->keys( self::KEYS['USER_LIMIT']. '*');
//        if ($allKeys && count($allKeys) > 0) {
//            for ($i = 0; $i < count($allKeys) ; $i++) {
//                RedisService::select(2)->del($allKeys[$i]);
//            }
//        }
//        $allKeys = '';
//        $allKeys = RedisService::select(2)->keys( self::KEYS['USER_GODTIME']. '*');
//        if ($allKeys && count($allKeys) > 0) {
//            for ($i = 0; $i < count($allKeys) ; $i++) {
//                RedisService::select(2)->del($allKeys[$i]);
//            }
//        }
//        $allKeys = '';
//        $allKeys = RedisService::select(2)->keys( 'user_god_ttl_'. '*');
//        if ($allKeys && count($allKeys) > 0) {
//            for ($i = 0; $i < count($allKeys) ; $i++) {
//                RedisService::select(2)->del($allKeys[$i]);
//            }
//        }
        $this->success('操作成功');
    }

    //移除所有用户黑名单         -- 清除勾选的用户限制,  目前没有做数据权限验证
    public function celarAllUserBlackList($id){
        foreach($id as &$val){
            RedisService::select(2)->del( self::KEYS['USER_BLACKLIST'] . "{$val}" );
        }
//        $allKeys = RedisService::select(2)->keys( self::KEYS['USER_BLACKLIST']. '*');
//        if ($allKeys && count($allKeys) > 0) {
//            for ($i = 0; $i < count($allKeys); $i++) {
//                RedisService::select(2)->del($allKeys[$i]);
//            }
//        }
        $this->success('操作成功');
    }


    //移除所有用户特权（提前抢购时间和提前抢购数量限制）     OK  -- _all 方法清除整个平台的用户, 慎用
    public function removeVip_all(){
        $allKeys = RedisService::select(2)->keys( self::KEYS['USER_LIMIT']. '*');
        if ($allKeys && count($allKeys) > 0) {
            for ($i = 0; $i < count($allKeys) ; $i++) {
                RedisService::select(2)->del($allKeys[$i]);
            }
        }
        $allKeys = '';
        $allKeys = RedisService::select(2)->keys( self::KEYS['USER_GODTIME']. '*');
        if ($allKeys && count($allKeys) > 0) {
            for ($i = 0; $i < count($allKeys) ; $i++) {
                RedisService::select(2)->del($allKeys[$i]);
            }
        }
        $allKeys = '';
        $allKeys = RedisService::select(2)->keys( 'user_god_ttl_'. '*');
        if ($allKeys && count($allKeys) > 0) {
            for ($i = 0; $i < count($allKeys) ; $i++) {
                RedisService::select(2)->del($allKeys[$i]);
            }
        }
        //获取所有用户特权使用 成功的键  所有场次
        $special_success = RedisService::select(2)->keys('special_success_*');
        foreach ($special_success as $sv){
            RedisService::select(2)->del( $sv);
        }


        $this->success('操作成功');
    }

    //移除所有用户黑名单     OK      -- _all 方法清除整个平台的黑名单, 慎用
    public function celarAllUserBlackList_all(){
        $allKeys = RedisService::select(2)->keys( self::KEYS['USER_BLACKLIST']. '*');
        if ($allKeys && count($allKeys) > 0) {
            for ($i = 0; $i < count($allKeys); $i++) {
                RedisService::select(2)->del($allKeys[$i]);
            }
        }
        $this->success('操作成功');
    }

    // 设置黑名单    --- TODO 暂时不用
    public function setBad($id, $isbad = 1){
        // bad=0 则删除, 1则添加
        if($isbad == 0){
            RedisService::select(2)->del( self::KEYS['USER_BLACKLIST'] . "{$id}");      // 必须字符串类型
        }else{
            RedisService::select(2)->hset( self::KEYS['USER_BLACKLIST'] . "{$id}");      // 必须字符串类型
        }
        return true;
    }

    // 设置权限表单页面 OK
    public function quanxian($id){

        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $this->setGodState($post) ;
                //print_r($re); die;
                //$save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }

        // TODO   查询之前的设定, 后期
         $data = self::getGodstate($id);
//print_r($data);die;
        $this->assign('id', $id );
        $this->assign('data', $data );
        return $this->fetch();

    }

    // 获取用户的上帝权限（单用户查看设置）
    // TODO  后期完善
    public function getGodstate($uid){
        //$uid = '363929'; // 我
        //$uid = '363449';        //  demo id

        $god = self::getUserGodState($uid);     // 已重写为数组形式
        $godttl = RedisService::select(2)->get('user_god_ttl_'."{$uid}" ); //await redis.Client2.get(`user_god_ttl_${uid}`);
//        print_r($god);die;
        if ($godttl) {
            try {
                $godttl = json_decode($godttl, true);
                //$god->ttl = $godttl;
                $god['ttl'] = $godttl;
            } catch(Exception $exception) {
                $data['ttl'] = 7;
                $data['time'] = date("Y-m-d H:i:s");
                //$god->ttl = json_encode($data) ;
                $god['ttl'] = $data;
            }
        } else {
            $data['ttl'] = 7;
            $data['time'] = date("Y-m-d H:i:s");
            //$god->ttl = json_encode($data) ;
            $god['ttl'] = $data;
        }
        return $god;
    }

    // 获取用户上帝模式的权限, 已重写为数组形式
    // TODO 后期完善
    private function getUserGodState($uid){

        $limit =            RedisService::select(2)->get( self::KEYS['USER_LIMIT'] . "{$uid}" );
        $limit_remain =     RedisService::select(2)->ttl( self::KEYS['USER_LIMIT'] . "{$uid}" );
        $blacklist =        RedisService::select(2)->get( self::KEYS['USER_BLACKLIST'] . "{$uid}" );
        $blacklist_remain = RedisService::select(2)->ttl( self::KEYS['USER_BLACKLIST'] . "{$uid}" );
        $blackroom =        RedisService::select(2)->get( self::KEYS['USER_BLACKROOM'] . "{$uid}" );
        $blackroom_remain = RedisService::select(2)->ttl( self::KEYS['USER_BLACKROOM'] . "{$uid}" );
        $godtime =          RedisService::select(2)->get( self::KEYS['USER_GODTIME'] . "{$uid}" );
        $godtime_remain =   RedisService::select(2)->ttl( self::KEYS['USER_GODTIME'] . "{$uid}" );

        $datalimit = [
            'use' => $limit !== null && $limit > 0 ? true : false,
            'data' =>  $limit > 0 ? $limit : 0,
            'timeout' => $limit_remain > 0 ? $limit_remain : 0
        ];
        $datablacklist = [
            'use' => $blacklist ? true : false,
            'data' =>  $blacklist  ? json_decode($blacklist, true) : [],
            'timeout' => $blacklist_remain > 0 ? $blacklist_remain : 0
        ];
        $datablackroom = [
            'use' => $blackroom ? true : false,
            'data' =>  $blackroom > 0 ? $blackroom : 0,
            'timeout' => $blackroom_remain > 0 ? $blackroom_remain : 0
        ];
        $datagodtime = [
            'use' => $godtime ? true : false,
            'data' =>  $godtime > 0 ? $godtime : 0,
            'timeout' => $godtime_remain > 0 ? $godtime_remain : 0
        ];
        $result = [
            'limit'=> $datalimit,
            'blacklist'=> $datablacklist,
            'blackroom' => $datablackroom,
            'godtime'=> $datagodtime
        ];
        return $result;
    }

    // 设置用户的上帝权限（单用户查看设置）   OK
    public function setGodState($postData){
        // DEMO json
        $demo = '{"limit":{"use":true,"data":2,"timeout":0},"blacklist":{"use":true,"data":[],"timeout":0},"blackroom":{"use":false,"data":0,"timeout":0},"godtime":{"use":true,"data":4,"timeout":0},"ttl":{"ttl":6,"time":"2022-10-22 18:09:18"},"uid":3850}';
        //    {
        //      "use": false,
        //      "data": 0,
        //      "timeout": 0
        //    }
        //    {
        //      "use": true,
        //      "data": 4,
        //      "timeout": 0
        //    }
        //    {
        //      "use": true,
        //      "data": 2,
        //      "timeout": 0
        //    }
        //    {
        //      "ttl": 6,
        //      "time": "2022-10-22 18:09:18"
        //    }
        // demo POST
//        $uid = $_POST['uid'];
//        $godtime = $_POST['godtime'];             // 秒
//        $blacklist = $_POST['blacklist'];       // 黑名单商品,   暂不考虑
//        $blackroom = $_POST['blackroom'];       //   暂不考虑
//        $limit = $_POST['limit'];                 // 抢购上限
//        $ttl = $_POST['ttl'] ? $_POST['ttl'] : ['ttl'=>1,'time'=> date("Y-m-d H:i:s") ] ;

        // demo test:
//        $test = json_decode($demo, true);
//        $uid = $test['uid'];
//        $godtime = $test['godtime'];
//        $blacklist = $test['blacklist'];       // 黑名单商品,   暂不考虑
//        $blackroom = $test['blackroom'];       //   暂不考虑
//        $limit = $test['limit'];
//        $ttl = $test['ttl'] ? $test['ttl'] : ['ttl'=>1,'time'=> date("Y-m-d H:i:s") ] ;

        // form post
        $limit_v = intval( $postData['limit'] ) ;
        $limit_v = $limit_v < 0 ? 0 : $limit_v;
        $god_v = intval( $postData['second'] ) ;
        $ttl_v = intval( $postData['day'] ) ;
        $uid = intval( $postData['uid'] ) ;

        $post_json = '{"limit":{"use":true,"data":'. $limit_v .',"timeout":0},
        "blacklist":{"use":false,"data":[],"timeout":0},
        "blackroom":{"use":false,"data":0,"timeout":0},
        "godtime":{"use":true,"data":'.$god_v.',"timeout":0},
        "ttl":{"ttl":'.$ttl_v.',"time":"'. date("Y-m-d H:i:s") .'"},
        "uid":'.$uid.'}';

        $post = json_decode($post_json, true);
        $uid = $post['uid'];
        $godtime = $post['godtime'];
        $blacklist = $post['blacklist'];       // 黑名单商品,   暂不考虑
        $blackroom = $post['blackroom'];       //   暂不考虑
        $limit = $post['limit'];
        $ttl = $post['ttl'] ? $post['ttl'] : ['ttl'=>1,'time'=> date("Y-m-d H:i:s") ] ;


        // TODO   @zyy
        // TODO  如上参数来源于提交表单, 格式为数组, 需要检查测试如下设置中数据格

        //   不会翻译了, 先放弃
        // 计算Timeout: 当前晚上12点过期
        //        let curTime = new Date();
        //        let y = curTime.getFullYear();
        //        let M = curTime.getMonth();
        //        let d = curTime.getDate();
        //        let expiresTime = new Date(y, M, d + parseInt(ttl.ttl), 0, 0, 0);
        //        let timeout = Math.floor((expiresTime.getTime() - curTime.getTime()) / 1000);


        $timeout = $ttl['ttl'] * 86400;     // n 天   x秒
        if ($godtime) {
            self::setUserGodTime($uid, $godtime['use'], $godtime['data'], $timeout);
        }
        if ($blacklist) {
            self::setUserBlackList($uid, $blacklist['use'], $blacklist['data'], $timeout);
        }
        if ($blackroom) {
            self::setUserBlackRoom($uid, $blackroom['use'], $timeout);
        }
        if ($limit) {
            self::setUserLimit($uid, $limit['use'], $limit['data'], $timeout);
        }

        $set = [
            'ttl'=> intval($ttl['ttl']),
            'time' => date("Y-m-d H:i:s")
        ];
        $data = json_encode($set);
//      $data = JSON.stringify({
//            ttl: parseInt(ttl.ttl),
//            time: moment().format('YYYY-MM-DD HH:mm:ss')
//        })

        RedisService::select(2)->setEx( 'user_god_ttl_'. $uid , $timeout, $data );

        return true;
    }

    // 设置用户的上帝权限（多用户查看设置）   OK
    public function setGodStates($postData){
        
        $ids = explode(",",$postData['uid']);
        foreach($ids as $id){
            // form post
            $limit_v = intval( $postData['limit'] ) ;
            $limit_v = $limit_v < 0 ? 0 : $limit_v;
            $god_v = intval( $postData['second'] ) ;
            $ttl_v = intval( $postData['day'] ) ;
            $uid = intval( $id ) ;

            $post_json = '{"limit":{"use":true,"data":'. $limit_v .',"timeout":0},
            "blacklist":{"use":false,"data":[],"timeout":0},
            "blackroom":{"use":false,"data":0,"timeout":0},
            "godtime":{"use":true,"data":'.$god_v.',"timeout":0},
            "ttl":{"ttl":'.$ttl_v.',"time":"'. date("Y-m-d H:i:s") .'"},
            "uid":'.$uid.'}';

            $post = json_decode($post_json, true);
            $uid = $post['uid'];
            $godtime = $post['godtime'];
            $blacklist = $post['blacklist'];       // 黑名单商品,   暂不考虑
            $blackroom = $post['blackroom'];       //   暂不考虑
            $limit = $post['limit'];
            $ttl = $post['ttl'] ? $post['ttl'] : ['ttl'=>1,'time'=> date("Y-m-d H:i:s") ] ;



            $timeout = $ttl['ttl'] * 86400;     // n 天   x秒
            if ($godtime) {
            self::setUserGodTime($uid, $godtime['use'], $godtime['data'], $timeout);
            }
            if ($blacklist) {
            self::setUserBlackList($uid, $blacklist['use'], $blacklist['data'], $timeout);
            }
            if ($blackroom) {
            self::setUserBlackRoom($uid, $blackroom['use'], $timeout);
            }
            if ($limit) {
            self::setUserLimit($uid, $limit['use'], $limit['data'], $timeout);
            }

            $set = [
            'ttl'=> intval($ttl['ttl']),
            'time' => date("Y-m-d H:i:s")
            ];
            $data = json_encode($set);
            //      $data = JSON.stringify({
            //            ttl: parseInt(ttl.ttl),
            //            time: moment().format('YYYY-MM-DD HH:mm:ss')
            //        })

            RedisService::select(2)->setEx( 'user_god_ttl_'. $uid , $timeout, $data );
        }
        

        return true;
    }

    // 设置用户抢购提前时间   OK
    private function setUserGodTime($uid, $use, $godtime, $timeout){
        if (!$use) {
            RedisService::select(2)->del( self::KEYS['USER_GODTIME'] . $uid );  //`${KEYS.USER_GODTIME}${uid}`);
        } else {
            RedisService::select(2)->setEx( self::KEYS['USER_GODTIME'] . $uid, $timeout, $godtime.'' );
        }

    }
    // 设置用户抢购商品限制   OK
    private function setUserBlackList($uid, $use, $blacklist, $timeout){
        if (!$use) {
            RedisService::select(2)->del(self::KEYS['USER_BLACKLIST'] . $uid) ;    //  (`${KEYS.USER_BLACKLIST}${uid}`);
        } else {
            RedisService::select(2)->setEx( self::KEYS['USER_BLACKLIST'] . $uid,  $timeout, json_encode($blacklist) );
        }
    }
    // 小黑屋  OK
    private function setUserBlackRoom($uid, $blackroom, $timeout){
        if (!$blackroom) {
            RedisService::select(2)->del(self::KEYS['USER_BLACKROOM'] . $uid) ;
        } else {
            RedisService::select(2)->setEx( self::KEYS['USER_BLACKROOM'] . $uid,  $timeout, '1' );
        }
    }
    //  设置用户抢购数量限制  OK
    private function setUserLimit($uid, $use, $limit, $timeout){
        if (!$use) {
            RedisService::select(2)->del(self::KEYS['USER_LIMIT'] . $uid );
        } else {
            RedisService::select(2)->setEx( self::KEYS['USER_LIMIT'] . $uid, $timeout,  json_encode($limit) );
        }
    }

    //  TODO: 重要功能!  批量将当前账号/仓下的用户, 更新他的邀请二维码
    public function sync_qrcode(){
        $admin  =  session("admin");

        // test
         // $admin['uid'] = 998 ;
        $list = $this->model
            //->whereRaw("bucket_id=:id1 OR bucket_id=:id2", ['id1' => $admin['uid'] , 'id2' => 0 ])
            ->where("bucket_id", 362918 )      // TODO:  这里不能or=0了, 否则会抢了其他仓的用户
//            ->where("id", 3850 )
            ->select();
        $r = [];
//         print_r($list);die;
        // 邀请二维码:    let qr_data = `${config.register_url}?rid=${user.uid}`

        foreach($list as &$item){
            $qr_url = Config::get('app.app_hostm') . '/register?rid=' . $item['id'] ;
//             echo $qr_url;die;
            // $qrData = str_replace("http://", "https://", $qr_url );
            $qrData = $qr_url ;           // TODO  配置文件已确认 https 或http, 这里不用处理

            $newData['qrcode'] = self::makeQrcode($item['id'], $qrData);
            $r[] = $this->model->where("id", $item['id'] )->update($newData);
            // echo Db::getLastSql();die;
        }
        $rows = count($r);
        $this->success("更新二维码成功数量:".$rows);
    }

    //  用url 生成二维码, 上传oss, 返回图片url

    /**
     * @param $sql_result      用户id记录文件名
     * @param $qr_data     邀请链接+参数
     * @return mixed
     * @throws \OSS\Core\OssException
     */
    public function makeQrcode($sql_result, $qr_data){
        $qrCode = new QRcode();

        $path = "./uploads/qrcode/" . $sql_result . ".png";
        if(!is_dir("uploads/qrcode/")){
            mkdir(iconv("UTF-8", "GBK","./uploads/qrcode/"),0777,true);
        }
        $qrCode->png($qr_data, $path, 10, "H");
//echo $path; die;
        $oss = ApiOss::getClient()->uploadFile('ferr-neo','qr-code/t_' .$sql_result .'_qr_'.time().'.jpg',app()->getRootPath().'public/uploads/qrcode/'.$sql_result . ".png");

        // print_r($oss);die;
        return $oss['info']['url']??'' ;
    }

    public function test11(){
        $list = $this->model
            ->where("bucket_id", 362918 )
            ->select();

        $qrCode = new QRcode();
        foreach($list as &$item) {
            $qr_data = Env::get('app.fronthost') . '?rid=' . $item['id'];
            //生成二维码

            $path = "./uploads/qrcode/" . $item['id'] . ".png";
            if (!is_dir("uploads/qrcode/")) {
                mkdir(iconv("UTF-8", "GBK", "./uploads/qrcode/"), 0777, true);
            }
            $qrCode->png($qr_data, $path, 10, "H");
            $oss = ApiOss::getClient()->uploadFile('luxiaxe', 'qr-code/' . $item['id'] . '_qr_' . time() . '.jpg', app()->getRootPath() . 'public/uploads/qrcode/' . $item['id'] . ".png");
            Db::name('user')->where('id', $item['id'])->update(['qrcode' => $oss['info']['url'] ?? '']);
        }
        // end

    }

}